<template>
  <div class="xtx-city"  ref="target">
    <div class="select" @click="toggleDialog" :class="{active: active}" >
      <span class="placeholder" v-if="!fullLocation">{{ placeholder }}</span>
      <span class="value" v-else>{{ fullLocation }}</span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div class="option"  v-if="active">
      <div class="loading" v-if="loading"></div>
      <template v-else>
        <span class="ellipsis" v-for="items in currList" :key="items.code" @click="itemsChange(items)" >
        {{ items.name }}
        </span>
      </template>
    </div>
  </div>
</template>

<script>
import { ref, computed, reactive } from 'vue'
import { onClickOutside } from '@vueuse/core'
import axios from 'axios'

// 获取城市数据
// 1.获取链接：https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json
// 2.何时获取：页面初始化的时候以及打开城市列表的时候
// 3.怎么使用数据？：定义计算属性，根据点击的省份城市进行展示
const getCityData = () => {
  // 这个位置可能有异常操作，封装成promise函数
  // resolve： 获取成功；reject：获取失败
  return new Promise((resolve, reject) => {
    if (window.cityData) {
      // 判断window中是否有缓存
      resolve(window.cityData)
    } else {
      // 无缓存的情况
      const url = 'https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json'

      // 发送请求
      axios.get(url).then(res => {
        window.cityData = res.data
        resolve(window.cityData)
      })
    }
  })
}
export default {
  name: 'XtxCity',
  props: {
    fullLocation: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择配送地址'
    }
  },
  setup (props, { emit }) {
    const active = ref(false) // 展开和收缩地址类表的开关

    const loading = ref(false) // 加载状态开关
    const cityData = ref([]) // 存储数据

    // 控制地址拉下菜单的展开收起 默认收起功能
    const openDialog = () => {
      active.value = true // 打开地址列表
      loading.value = true

      // 获取数据
      getCityData().then(data => {
        cityData.value = data
        loading.value = false
      })

      // 清空地址列表历史选择
      for (const key in changeResult) {
        changeResult[key] = ''
      }
      console.log(active.value, '3')
    }
    const closeDialog = () => {
      active.value = false
    }
    // 切换展开收起
    const toggleDialog = () => {
      if (active.value) closeDialog()
      else openDialog()
    }

    // 控制点击其他位置时 下拉菜单经行隐藏
    const target = ref(null)
    onClickOutside(target, () => {
      closeDialog()
    })

    // 定义计算属性
    const currList = computed(() => {
      // 省份
      let currList = cityData.value
      // 判断是否点击省份 点击省份之后显示市级类表
      if (changeResult.provinceCode) {
        console.log(changeResult.provinceCode)
        // 查询目标值 并返回一个子类数组
        currList = currList.find(p => p.code === changeResult.provinceCode).areaList
      }

      // 点击市级之后显示市级地区
      if (changeResult.cityCode) {
        currList = currList.find(p => p.code === changeResult.cityCode).areaList
      }

      // TODO 根据点击的不同省份获取不同的列表
      return currList
    })

    // 定义初始化时的地址变量的值
    const changeResult = reactive({
      provinceCode: '',
      provinceName: '',
      cityCode: '',
      cityName: '',
      countyCode: '',
      countyName: '',
      fullLocation: ''
    })

    const itemsChange = (items) => {
      // 省
      if (items.level === 0) {
        changeResult.provinceCode = items.code
        changeResult.provinceName = items.name
      }

      // 市
      if (items.level === 1) {
        changeResult.cityCode = items.code
        changeResult.cityName = items.name
      }

      // 地区
      if (items.level === 2) {
        changeResult.countyCode = items.code
        changeResult.countyName = items.name
        changeResult.fullLocation = `${changeResult.provinceName} ${changeResult.cityName} ${changeResult.countyName}`
        closeDialog()
        emit('change', changeResult)
      }
    }

    return { toggleDialog, active, target, loading, currList, itemsChange }
  }
}
</script>

<style lang="less" scoped>
.xtx-city {
  display: inline-block;
  position: relative;
  z-index: 400;
  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    cursor: pointer;
    &.active {
      background: #fff;
    }
    .placeholder {
      color: #999;
    }
    .value {
      color: #666;
      font-size: 12px;
    }
    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }
  .option {
    width: 542px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top:29px;
    background: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    // 添加加载中样式
    .loading {
      height: 290px;
      width: 100%;
      background: url(../../assets/images/loading.gif) no-repeat center;
    }
    >span {
      width: 130px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      padding: 0 5px;
      &:hover {
        background: #f5f5f5;
      }
    }
  }
}
</style>
